package lesson3.slides.xml.dom;

import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomParserExample {

    public static Document d;
    
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("something.xml");

        DocumentBuilder db =
                DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();

        d = db.parse(fis); // d is root Node

        processNode(d, 0); // investigate the document tree

    }

    private static void processNode(Node n, int level) {
        System.out.println(indent(level) + "nodeName="
                + n.getNodeName() +" nodeValue="+n.getNodeValue());
        NodeList nList = n.getChildNodes();
        int count = nList.getLength();
        for (int i = 0; i < count; i++) {
            processNode(nList.item(i), level + 1);
        }
    }

    private static String indent(int level) {
        String[] spaces = {"", "  ", "    ", "      ",
            "        ", "          ", "            "};
        if (level < spaces.length) {
            return spaces[level];
        } else {
            return spaces[spaces.length - 1] + indent(level - spaces.length + 1);
        }
    }
}